package com.ciaojian.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.core.enums.business.WorkerApplyStatusEnum;
import com.ciaojian.core.model.Scheduling;
import com.ciaojian.core.model.SchedulingExamine;
import com.ciaojian.core.util.Result;
import com.ciaojian.store.model.query.ScheduleExamineQuery;
import com.ciaojian.store.service.SchedulingExamineServiceImpl;
import com.ciaojian.store.service.SchedulingServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author Atlakyn
 */
@Api(tags = "排班审核")
@RestController
@RequestMapping("/schedules")
public class SchedulingExamineController {
    @Resource
    private SchedulingServiceImpl schedulingService;
    @Resource
    private SchedulingExamineServiceImpl schedulingExamineService;

    @ApiOperation(value = "审核详情", response = Scheduling.class)
    @GetMapping("/examines/detail/{examineId}")
    public Result getDetail(@ApiParam(value = "审核记录id") @PathVariable Integer examineId) {
        return Result.ok(schedulingService.getBaseMapper().findByExamineId(examineId));
    }

    @ApiOperation(value = "审核列表", response = SchedulingExamine.class)
    @GetMapping("/examines")
    public Result getList(WorkerApplyStatusEnum status,
                          @RequestParam(defaultValue = "0") Integer pageNo,
                          @RequestParam(defaultValue = "6") Integer pageSize) {
        LambdaQueryWrapper<SchedulingExamine> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SchedulingExamine::getStatus, status)
                .eq(SchedulingExamine::getLogicDel, Boolean.FALSE)
                .orderByDesc(SchedulingExamine::getCreateTime);
        return Result.ok(schedulingExamineService.page(new Page<>(pageNo, pageSize), lambdaQueryWrapper));
    }

    @ApiOperation("审核排班申请")
    @Validated
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/examine/{examineId}")
    public Result examine(@ApiParam(value = "排班申请Id") @PathVariable Integer examineId,
                          @RequestBody ScheduleExamineQuery query) {
        SchedulingExamine schedulingExamine = new SchedulingExamine().selectById(examineId);
        Assert.isTrue(WorkerApplyStatusEnum.WAIT.equals(schedulingExamine.getStatus()), "本次申请已审核!");

        schedulingExamineService.audit(schedulingExamine, query, examineId);

        return Result.ok();
    }
}
